//
//  NSString+URL.m
//  HGMM
//
//  Created by 2008-bj5 on 15/8/27.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "NSString+URL.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (URL)

- (NSString *)URLEncodedString {
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)self,
                                            (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                            NULL,
                                            kCFStringEncodingUTF8));
    return encodedString;
}

-(NSString *) md5 {
    const char *original_str = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash lowercaseString];
}

-(NSString *)getFileExt{
    NSDictionary *dic = @{
                          @".doc":    @"application/msword",
                          @".docx":   @"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                          @".xls":    @"application/vnd.ms-excel",
                          @".xlsx":   @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                          @".pdf":    @"application/pdf",
                          @".png":    @"image/png",
                          @".pps":    @"application/vnd.ms-powerpoint",
                          @".ppt":    @"application/vnd.ms-powerpoint",
                          @".pptx":   @"application/vnd.openxmlformats-officedocument.presentationml.presentation",
                          @".bmp":   @"image/bmp",
                          @".gif":    @"image/gif",
                          @".jpeg":   @"image/jpeg",
                          @".jpg":    @"image/jpeg",
                          };
    NSArray *keyArr = [dic allKeys];
    NSArray *valueArr = [dic allValues];
    NSMutableString *fileExt = [NSMutableString stringWithString:self];
    if (![self hasPrefix:@"."]) {
        [fileExt insertString:@"." atIndex:0];
    }
    if ([keyArr containsObject:fileExt]) {
        return fileExt;
    }
    if ([valueArr containsObject:self]) {
        return [dic allKeysForObject:self][0];
    }
    return nil;
}

@end
